package org.ecinc.mvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ecinc.mvc.form.ActionForm;
import org.ecinc.mvc.form.FillForm;
import org.ecinc.mvc.util.XMLBean;

public class ActionServlet extends HttpServlet{

	private static final long serialVersionUID = -6718305147817206076L;

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String path = this.getPath(request.getServletPath());
		Map<String, XMLBean> map = (Map<String, XMLBean>) request.getSession().getServletContext().getAttribute("struts");
		XMLBean bean = map.get(path);
		String formClass = bean.getFormClass();
		ActionForm form = FillForm.fill(formClass, request);
		String actionClass = bean.getActionClass();
		String url = "";
		
		try {
			Class clazz = Class.forName(actionClass);
			Action action = (Action) clazz.newInstance();
			url = action.execute(request, response, form, bean.getActionForward());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}
	
	private String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
}
